package cn.hiapi.shopkeeper.service.order;

import cn.hiapi.basic.entity.BasicEntity;
import cn.hiapi.basic.jpa.pageable.QueryWrapper;
import cn.hiapi.basic.service.AbsBasicService;
import cn.hiapi.basic.token.Token;
import cn.hiapi.shopkeeper.entity.order.ActivityBargainRecord;
import cn.hiapi.shopkeeper.jpa.order.ActivityBargainRecordJpa;
import cn.hiapi.utils.JsonUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author AdinZ
 * @date 2023/1/10 11:33
 */
@Service
public class ActivityBargainRecordService extends AbsBasicService<ActivityBargainRecordJpa, ActivityBargainRecord, Long> {
    private final String KEY = "CORE:ACTIVITY:BARGAIN_RECORD";


    private String getKey(long oid, long uid) {
        return new StringBuffer().append(oid).append("_").append(uid).toString();
    }

    public boolean exists(long oid, long uid) {
        ActivityBargainRecord o = redisService.get(KEY, getKey(oid, uid));
        if (o != null) return true;
        List<ActivityBargainRecord> list = findList(new QueryWrapper().eq("oid", oid).eq("uid", uid));
        return !list.isEmpty();
    }


    @Override
    public ActivityBargainRecord save(ActivityBargainRecord record) {
        super.save(record);
        this.redisService.set(KEY, this.getKey(record.getOid(), record.getUid()), record);
        return record;
    }

    /**
     * 统计砍价数量
     *
     * @param oid
     * @return
     */
    public Total total(long oid) {
        JSONObject data = this.repository.totalOrder(oid);
        Total total = new Total();
        if (data == null) return total;
        total.setTotalPrice(JsonUtils.getBigDecimal(data, "totalPrice"));
        total.setCount(JsonUtils.getLong(data, "count"));
        return total;
    }

    /**
     * 参与人数
     * @param aid
     * @return
     */
    public long getParticipate(long  aid) {
        return this.count(new QueryWrapper().eq("aid",aid)  );
    }


    @Setter
    @Getter
    public static class Total extends BasicEntity {
        private long count;
        private BigDecimal totalPrice = BigDecimal.ZERO;
    }


}
